package zwp.exercise.service.exercisedemo.chapterFour.PracticeAndExercises;

import zwp.exercise.service.exercisedemo.chapterThree.constants.CommonConstants;
import zwp.exercise.service.utils.IdleTimeoutUtils;

import java.util.Scanner;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.atomic.AtomicLong;

/**
 * @Author zwp14
 * @create 2025/11/26 20:51
 * @description 判断奇偶数
 * 输入一个数，判断是奇数还是偶数
 */
public class FirstExerciseDemo {

    public static void main(String[] args) {
        // 业务计时器，一定时间后业务自动关闭，计时器还可再优化可参考zwp.exercise.service.exercisedemo.chapterThree.basicdatatypes.BMIexponent
        ScheduledExecutorService scheduledExecutorService = IdleTimeoutUtils
                .startBusiness(CommonConstants.IDLE_TIMEOUT_MS, new AtomicLong(System.currentTimeMillis()));
        System.out.println("或者用户输入三次后自动关闭！");

        // 奇数偶数判断依据，取余
        int two = 2;
        // 判断不超过三次（后期优化可去掉，只用计时器）
        int three = 3;
        // 计数器（后期优化可去掉，只用计时器）
        int countNum = 0;
        // 创建一个系统输入
        try (Scanner scanner = new Scanner(System.in)) {
            executeBusiness(two, three, countNum, scanner);
        } finally {
            scheduledExecutorService.shutdown();
        }


    }

    /**
     * @param two 常量
     * @param three 常量
     * @param countNum 计数器
     * @param scanner 用户输入
     */
    private static void executeBusiness(int two, int three, int countNum, Scanner scanner) {
        int num;
        System.out.println("请输入您要判断的数据：");
        // 如果用户输入有误将进行循环操作。最多循环操作3次。
        do {
            countNum += 1;
            // 获取系统输入

            String input = scanner.next();
            try {
                // 解析为int类型
                num = Integer.parseInt(input);
                // 异常捕获，并赋值默认值 Integer.MIN_VALUE。
            } catch (NumberFormatException e) {
                System.out.println("输入有误, 请重新输入！");
                num = Integer.MIN_VALUE;
            }

        } while (num == Integer.MIN_VALUE && countNum < three);

        if (countNum == three && num == Integer.MIN_VALUE) {
            System.out.println("重新输入次数超过三次，系统自动关闭！");
        } else if (num % two == 0) {
            System.out.println("您输入的数" + num + "为偶数！");
        } else {
            System.out.println("您输入的数" + num + "为奇数！");
        }
    }
}
